package com.iflysse.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.iflysse.pojo.Node;

/**
 * Servlet Filter implementation class PwFilter
 */

public class PwFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public PwFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;

		String path = req.getRequestURI();
		// System.out.println("---------------------");
		// System.out.println(path);
		// System.out.println("---------------------");
		// 进入首页请求不放行页面
		if (path.contains("/login/LoginRequestServlet.do")
				|| (path.contains("/login/LoginIndexRequestServlet.do"))
				|| path.contains("/login/LoginHandlerServlet.do")
				|| path.contains("/login/RegisterServlet.do")
				|| path.contains("/user/userInfo.do")
				|| path.contains("/user/ShowUserRoleServlet.do")) {
			chain.doFilter(req, resp);
			return;
		} else { // 需要拦截页面

			HttpSession session = req.getSession();
			List<Node> menus = (List<Node>) session.getAttribute("menu");
			List<String> pwlist = new ArrayList<String>();

			for (Node node : menus) {
				String uri = node.getMenuIno().getMenuUrl();
				pwlist.add(uri.split("/")[0]);
			}
			System.out.println(pwlist);
			System.out.println(path.split("/")[2]);
			if (pwlist.contains(path.split("/")[2])) {
				chain.doFilter(req, resp);
			} else {
				resp.sendRedirect(req.getContextPath()
						+ "/login/LoginRequestServlet.do");
			}

		}

	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
